<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

/**
 * 卡位模块（抢排名）
 * Author: Boya
 */
require_once APP_PATH . 'Lib/Library/Ranking.class.php';
require_once APP_PATH . 'Lib/Library/Paging.class.php';

class RankingAction extends NewzanAction
{
	//初始化函数
	function _initialize()
	{
		parent::_initialize();
		$this->ranking = new Ranking();
	}

	//得关键词现在价格
	function AjaxGetCurrentValue()
	{
		//接收传值
		$keyword_ids = $this->_param('keyword_ids');
		// dump($keyword_ids);
		$res = $this->ranking->getCurrentValue($this->me['user_id'],$keyword_ids);
		echo json_encode($res);
	}

	//恢复原价
	function restoreOriginalValue()
	{	
		try{
			//接收传值
			$tactics_id = trim($this->_param('tactics_id'));
			$keyword_ids = $this->_param('keyword_ids');

			//查询原始价格
			$originalValues = $this->ranking->getOriginalValue($tactics_id,$keyword_ids);
			
			//竞拍
			$campaign_infos = '';
			foreach ($originalValues as $key => $msg) {
				# code...
				$campaign_infos[$keyword_ids[$key]] = $msg['original_value'];
			}
			$res = $this->ranking->campaign($this->me['user_id'],$campaign_infos);

			//竞拍成功
			if ($res) {
				//修改want_rank表内容
				//清除msg
				$want_rank = M('want_rank');
				$update_res = $want_rank->execute("UPDATE want_rank SET msg=NULL where tactics_id = $tactics_id");
				if ($update_res === false) {
					throw new Exception("恢复原价->修改want_rank表内容msg失败", 1);
				}

				//修改doing
				$queryStr = implode(',',$keyword_ids);
				$where = "keyword_id IN ($queryStr) AND doing = '3'";
				$keyword_ids_res = $want_rank->field('keyword_id')->where($where)->select();

				// dump($keyword_ids_res);
				// die();
				
				if ($keyword_ids_res) {
					$update = '';
					foreach ($keyword_ids_res as $key => $msg) {
						$update[] = $msg['keyword_id'];
					}
					$keyword_ids_str = implode(',',$update);
					$update_res = $want_rank->execute("UPDATE want_rank SET doing=0 where keyword_id IN ($keyword_ids_str)");

					// dump($want_rank->getLastSql());
					// die();

					if ($update_res == false) {
						throw new Exception("恢复原价->修改want_rank表内容doing失败", 1);
					}
				}
			}else{

			//竞拍失败
				throw new Exception("恢复原价->竞拍失败", 5);
			}

			$this->display_json(array('code' => 1, 'msg' => '恢复原价'));		
		}catch(Exception $e){
			$errorMsg = '';
			switch ($e->getCode()) {
				case '4':
					$keywords = M('keywords'.$this->me['user_id']);
					$where = "keyword_id = {$e->getMessage()}";
					$words = $keywords->field('word')->where($where)->limit(1)->select();
					$word = $words[0]['word'];
					$errorMsg = "恢复原价失败! 没有设置原价,关键词: $word";
					$this->ranking->printError($errorMsg);
					break;
				case '1':
				case '5':
					$errorMsg = $this->ranking->getErrorMessage($e);
					break;
				default:
					break;
			}
			$this->ranking->printError($e);
		    $this->display_json(array('code' => 0, 'msg' => $errorMsg));
		}
	}

	//得卡位关键词的报表
	function getRankWordReport()
	{
		try{
			$the_date = date('Y-m-d');
			$date_start = $this->ranking->check_date($this->_param('date_start'));
			$date_end = $this->ranking->check_date($this->_param('date_end'));

	        if (strtotime($date_start) == strtotime($the_date)) {  //取今天的数据
		        $keyWordModel = new KeywordModel();
				$res = '';
				$request = '';  //合并请求(去掉重复的(campaign_id.adgroup_id))
				foreach ($this->_param('adgroupCampaign_id') as $msg) {
					if (!isset($request[$msg['campaign_id'].$msg['adgroup_id']])) {
						$request[$msg['campaign_id'].$msg['adgroup_id']] = 1;
						$temp = $keyWordModel->getWordReport($msg['campaign_id'],$msg['adgroup_id']);
						foreach ($temp as $msg) {
							$res[] = (array)$msg;
						}
					}
				}

				//过滤
				$filter = '';
				foreach ($res as $key=>$msg) {
					foreach ($this->_param('adgroupCampaign_id') as $msg_param) {
						if ($msg['bidwordid'] == $msg_param['keyword_id']) {
							$filter[] = $msg;
						}
					}
				}

				//汇总数据
				$gather = '';
				foreach ($filter as $msg) {

					//展现量
					$this->_sum($gather[$msg['bidwordid']]['impression'],$msg['impression']);

					//点击量
					$this->_sum($gather[$msg['bidwordid']]['click'],$msg['click']);

					//总花费
					$this->_sum($gather[$msg['bidwordid']]['cost'],$msg['cost']);

					//收藏数
					$this->_sum($gather[$msg['bidwordid']]['favtotal'],$msg['favtotal']);

					//购物车数
					$this->_sum($gather[$msg['bidwordid']]['carttotal'],$msg['carttotal']);

					//总成交金额(元)
					$this->_sum($gather[$msg['bidwordid']]['transactiontotal'],$msg['transactiontotal']);

					//总成交笔数
					$this->_sum($gather[$msg['bidwordid']]['transactionshippingtotal'],$msg['transactionshippingtotal']);

				}

				//点击率ctr(点击量/展现量)
				//每点击花费cpc,ppc(总花费/点击量)
				//投入产出比roi(总成交金额/总花费)
				foreach ($gather as $key => &$value) {
					$ctr = $value['click']/$value['impression'] ? $value['click']/$value['impression'] : 0;
					$ctr = $ctr*100;
					$value['cost'] = $value['cost'] ? $value['cost']/100 : $value['cost'];
					$value['ctr'] = $this->ranking->_numFormat($ctr);
					$value['cpc'] = $this->ranking->_numFormat(($value['cost']/$value['click'] ? $value['cost']/$value['click'] : 0)/100);
					$value['roi'] = $this->ranking->_numFormat(($value['transactiontotal']/$value['cost'] ? $value['transactiontotal']/$value['cost'] : 0));
				}

				// dump($res);
				// dump($filter);
				// dump($gather);
				// die();
				echo json_encode($gather);
		    }else{
		    	$keyword_ids = '';
		    	foreach ($this->_param('adgroupCampaign_id') as $msg_param) {
		    		$this->ranking->check_user_id($msg_param['keyword_id']);
		    		$keyword_ids[] = $msg_param['keyword_id'];
				}
				$res = $this->ranking->getWordOldReport($keyword_ids,$date_start,$date_end);
		    	echo json_encode($res);
		    }
		}catch(Exception $e){
			$this->ranking->printError($e);
		    $this->display_json(array('code' => 0, 'msg' => $errorMsg));
		}
		
	}
	
	// private function _numFormat($num)
	// {
	// 	if (is_float($num)) {
	// 		return round($num,2);
	// 	}else{
	// 		return $num;
	// 	}
	// }

	private function _sum(&$sumPoint,$addNum)
	{
		if(is_null($addNum)) $addNum = 0;
		if (isset($sumPoint)) {
			$sumPoint += $addNum;
		}else{
			$sumPoint = $addNum;
		}
	}

	//删除卡位策略
	function delTacticsByTacticsId()
	{
		try{
			//接收传值
			$user_id = $this->me['user_id'];
			$tactics_id = $this->_param('tactics_id');

			//权限判断
			if ($this->ranking->auth($user_id,$tactics_id)) {
				//实例化数据映射器
				$tactics = M('tactics');
				$want_rank = M('want_rank');
			    // $adgroup_tactics_map = M('adgroup_tactics_map');

			    //执行删除
			    //开启事务
		        $tactics->startTrans();
		        $where['tactics_id'] = $tactics_id;
		        $tactics_delRes = $tactics->where($where)->delete();
		        $want_rank_delRes = $want_rank->where($where)->delete();
		        // $adgroup_tatics_map_delRes = $adgroup_tactics_map->where($where)->delete();
		        if (($tactics_delRes === false) || ($want_rank_delRes === false) || ($adgroup_tatics_map_delRes === false)) {
		        	throw new Exception("删除卡位策略失败", 1);	
		        }
			}else{
				throw new Exception('无权操作',2);
			}
			//提交事务
			$tactics->commit();
			// echo '删除成功';
			$this->display_json(array('code' => 1, 'msg' => '删除成功'));
		}catch(Exception $e){
			if($tactics){
				$tactics->rollback();
			}
			$this->ranking->printError($e);
		    $this->display_json(array('code' => 0, 'msg' => $this->ranking->getErrorMessage($e)));
		}
	}

	//暂停\开启卡位策略
	function playOrStopTactics()
	{
		try{
			//接收传值
			$user_id = $this->me['user_id'];
			$tactics_id = $this->_param('tactics_id');
			$tactics_status = $this->_param('tactics_status');  //策略状态: 1->开启, 2->暂停
			if (!preg_match('/^[1-2]$/',$tactics_status) || is_null($tactics_id)) {
				throw new Exception('tactics_status格式不符合要求',3);
		    }

			//权限判断
			$auth_res = $this->ranking->auth($user_id,$tactics_id);
			if ($auth_res['tactics_status'] != $tactics_status) {
				$tactics = M("tactics");
				$auth_res['tactics_status'] = $tactics_status;
				if ($tactics->save($auth_res)===false) {
					//添加失败,抛出错误
					throw new Exception('tactics更新失败'.$tactics->getLastSql(),1);
				}	
			}
			$this->display_json(
					array(
							'code' => 0,
							'msg' => (int) $tactics_status == 1 ? '开启成功' : '暂停成功'
						)
				);
		}catch(Exception $e){
			$this->ranking->printError($e);
		    // $this->display_json(array('total_items' => 0, 'items' => $this->ranking->getErrorMessage($e)));
		    $this->display_json(
		    		array(
		    				'code' => 1,
		    				'msg' => $this->ranking->getErrorMessage($e)
		    			)
		    	);
		}
	}

	//按策略id显示卡位信息
	function showTacticsByTacticsId()
	{
		try{
			$paging = new Paging();

			//接收传值
			$tactics_id = $this->_param('tactics_id');

			if ($this->_param('pageSize') && preg_match('/^\d*$/',$this->_param('pageSize'))) $paging->pageSize = $this->_param('pageSize');
			if ($this->_param('pageNow') && preg_match('/^\d*$/',$this->_param('pageNow'))) $paging->pageNow = $this->_param('pageNow');

			//权限判断
			if (!$this->ranking->auth($this->me['user_id'],$tactics_id)) {
				throw new Exception('无权访问',2);
			}

			// echo 'mlkr2';
			// die();

			//通过策略id查询策略信息
			$this->ranking->getRankInfo(new GetRankViewBytacticsId($this->me['user_id'],$tactics_id,$paging));
			// dump($paging);
			// die();
			// $this->display_json($paging);
			$this->assign('res',$paging->getRes_array());
			$this->display('rankingDetail'); 

		}catch(Exception $e){
			$this->ranking->printError($e);
		    $this->display_json(array('total_items' => 0, 'items' => $this->ranking->getErrorMessage($e)));
		}
	}

	//按用户id显示卡位策略
	private function _showTacticsByUserId()
	{
		try{
			$paging = new Paging();

			//接收传值
			if ($this->_param('pageSize') && preg_match('/^\d*$/',$this->_param('pageSize'))) $paging->pageSize = $this->_param('pageSize');
			if ($this->_param('pageNow') && preg_match('/^\d*$/',$this->_param('pageNow'))) $paging->pageNow = $this->_param('pageNow');

			//检查格式
			$this->ranking->check_user_id($this->me['user_id']); 

			//查询卡位策略
			$tactics = M('tactics');  //实例化数据映射器
			$where['user_id'] = $this->me['user_id'];
			$field = array('tactics_id','tactics_name','tactics_status','executions','tactics_modified_time','path', 'from', 'to');
			$paging->setRowCount($tactics->field($field)->where($where)->count());
			$paging->setPageCount(ceil($paging->getRowCount()/$paging->getPageSize()));
			$paging->setRes_array($tactics->field($field)->where($where)->limit($paging->getOffset().','.$paging->getPageSize())->order('tactics_id DESC')->select());

			// $tactics_ids = $this->ranking->changeTo_ODarray($tactics->field('tactics_id')->where($where)->select());
			
			// //通过策略id查询策略信息
			// $this->ranking->getRankingBytacticsId($this->me['user_id'],$tactics_ids,$paging);
			// dump($paging);
			// $this->display_json($paging);
			return (array) $paging;

	    }catch(Exception $e){
	    	$this->ranking->printError($e);
	    	// $this->display_json(array('total_items' => 0, 'items' => $this->ranking->getErrorMessage($e)));
	    	return array(
	    			'rowCount' => 0,
	    			'msg' => $this->ranking->printError($e)
	    		);
		    // $this->display_json($e->getMessage());
	    }
	}


	//添加策略页面 
	function addTactics()
	{
		$this->show();
	}

	//更新策略
	function editTactics() 
	{
		$this->show();
	}

	//添加\编辑卡位策略
	function save()
	{
		try{
			//接收传值
			//tactics表
			$tactics_data['tactics_id'] = $this->_post('tactics_id');
			$tactics_data['user_id'] = $this->me['user_id'];
			$tactics_data['tactics_name'] = $this->_post('tactics_name');
			$device = $this->_post('device');
			if(!$device || ($device < 0 && $device > 1)){
				$device = 0;
			}
			$tactics_data["device"] = $device;
			$from = $this->_post('from');
			$to = $this->_post('to');
			if($from && $to) {
				$tactics_data['from'] = $from ? strtotime(str_replace('T', ' ', $from)) : '';
				$tactics_data['to'] = $to ? strtotime(str_replace('T', ' ', $to)) : '';
			}

			if ($this->_post('tactics_status')) {
				if (!preg_match('/^[1-3]$/',$this->_post('tactics_status'))) {
					throw new Exception('tactics_status格式不符合要求',3);
				}
				$tactics_data['tactics_status'] = $this->_post('tactics_status');
			}

			$tactics_data['premium'] = $this->_post('premium');  //溢价,array('type'=>'',value=>''),type:1->数值,2->百分比

			if (!$this->ranking->check_premium($tactics_data['premium']['value'])) {
				throw new Exception('premium格式不符合要求',3);
			}

			// if (!preg_match('/^([-+]?\d+)(\.\d+)?\%?$/',$tactics_data['premium']['value'])) {					
			// 	throw new Exception('premium格式不符合要求',3);
			// }

			if ($tactics_data['premium']['type'] == 2) {
				$tactics_data['premium'] = ($tactics_data['premium']['value']/100).'%';
			}else{
				$tactics_data['premium'] = $tactics_data['premium']['value'];
			}

			$tactics_data['campaign_period'] = $this->_post('campaign_period');
			$tactics_data['heighest_price'] = $this->_post('heighest_price');
			
			//want_rank表
			$want_rank_data['want_rank'] = I('want_rank');

			// //adgroup_tatics_map表
			// $adgroup_tatics_map_data['adgroup_id'] = $this->_post('adgroup_id');

			//实例化数据映射器
			$tactics = M('tactics');
			$want_rank = M('want_rank');
		    // $adgroup_tactics_map = M('adgroup_tactics_map');
		    $keywords = M('keywords'.$this->me['user_id']);

		    //处理数据
		    $keyword_ids = '';
		    foreach ($want_rank_data['want_rank'] as $keyword_id => $want_rank_value) {
					$keyword_ids[] = $keyword_id;
				}

			$tactics_data['keyword_ids'] = implode(",",$keyword_ids);
			$tactics_data['tactics_create_time'] = time();
			$tactics_data['tactics_modified_time'] = 0;

			//开启事务
			//(注意:mysql不支持多层事务,这里采用laravel的做法,只在最外层开启事务)
			$tactics->startTrans();

	        //判断是编辑策略还是添加策略
	        $notify = array(
	        		'code' => 0,
	        		'msg' => '修改失败!'
	        	);
			if($tactics_data['tactics_id']){

				//编辑策略
				$tactics_res = $this->ranking->auth($tactics_data['user_id'],$tactics_data['tactics_id']);  //权限判断
				if (!$tactics_res) {
					throw new Exception('无权编辑',2);
				}

				//tactics表
				if($tactics->save($tactics_data) === false){
					//更新失败
					throw new Exception('tactics更新失败'.$tactics->getLastSql(),1);
				}
					//want_rank表
					$where['tactics_id'] = $tactics_data['tactics_id'];
					$find = $want_rank->field('keyword_id')->where($where)->select();
					$find = array_column($find, 'keyword_id');
					
					if($find) {
						// 删除已经不在的关键词
						foreach ($find as $keyword_id) {
							if(!isset($want_rank_data['want_rank'][$keyword_id])) {
								$want_rank->where(array('tactics_id' => $tactics_data['tactics_id'], 'keyword_id'=> $keyword_id))->delete();
							}
						}
					}

					foreach ($want_rank_data['want_rank'] as $keyword_id => $want_rank_value) {
						// 插入新词
						if(!in_array($keyword_id, $find)) {
							$want_rank_data_insert = array();
							$want_rank_data_insert['tactics_id'] = $tactics_data['tactics_id'];
							$want_rank_data_insert['keyword_id'] = $want_rank_value['keyword_id'];
							$want_rank_data_insert['want_rank'] = $want_rank_value['want_rank'];
							$want_rank_data_insert['doing'] = 0;
							$want_rank_data_insert['msg'] = '';
							$want_rank_data_insert['update_time_keyword'] = '';
							$want_rank->add($want_rank_data_insert);
						} else {
							// 更新旧词
							$this->ranking->check_want_rank_data($keyword_id,$want_rank_value['want_rank']);  //检查格式
							$where['keyword_id'] = $keyword_id;
							$want_rank_data_updata = array();
							$want_rank_data_updata['want_rank'] = $want_rank_value['want_rank'];
							$want_rank_data_updata['doing'] = 0;
							$want_rank_data_updata['msg'] = '';
							$want_rank_data_updata['update_time_keyword'] = '';	
							if ($want_rank->where($where)->save($want_rank_data_updata)===false) {
								//更新失败,抛出错误
								throw new Exception("want_rank更新失败!".$want_rank->getLastSql(),1);
							}
						}
					}
				$notify['msg'] = '编辑成功!';
				$notify['code'] = 1;

			}else{
				//添加策略
				$tactics_data['path'] = $this->_post('path');
				//tactics表
				unset($tactics_data['tactics_id']);
				$tactics_id = $tactics->add($tactics_data);

				if(!$tactics_id){
					//添加失败
					throw new Exception('tactics添加失败',1);
				}

				//得关键词当前出价
				$currentValue = $this->ranking->getCurrentValue($this->me['user_id'],$keyword_ids);

		        //want_rank表(批量插入)
				$want_rank_data_list = '';
				foreach ($keyword_ids as $key=>$msg) {					
					$this->ranking->check_want_rank_data($want_rank_data['want_rank'][$msg]['keyword_id'],$want_rank_data['want_rank'][$msg]['want_rank']);  //检查格式
					$want_rank_data_info['keyword_id'] = $msg;
					$want_rank_data_info['want_rank'] = $want_rank_data['want_rank'][$msg]['want_rank'];
					$want_rank_data_info['tactics_id'] = $tactics_id;
					$want_rank_data_info['original_value'] = $currentValue[$key]['max_price'];
					$want_rank_data_list[] = $want_rank_data_info;
				}

				if (!$want_rank->addAll($want_rank_data_list)) {
					//添加失败,抛出错误
					throw new Exception("want_rank批量添加失败!",1);
				}

			 //    //adgroup_tatics_map表
				// $adgroup_tatics_map_data['tactics_id'] = $tactics_id;
				
				// //添加记录之前,应该用adgroup_id去查keyworld表,
				// //得到keyworld_id与传来的$keyworld_id比较,如果不同,则传来的数据有误
				// $this->ranking->check_user_id($adgroup_tatics_map_data['adgroup_id']);  //检查格式
				// $where['adgroup_id'] = $adgroup_tatics_map_data['adgroup_id'];
				// $keyword_ids_res = $keywords->field('keyword_id')->where($where)->select();
				// $keyword_ids_res = $this->ranking->changeTo_ODarray($keyword_ids_res);
				// if (array_diff($keyword_ids, $keyword_ids_res)) {
				// 	//如果接受到的关键词id和查询得到的关键词id有差集,
				// 	//说明传入的关键词id有误
				// 	throw new Exception('传入的关键词id有误',4);
				// }

				// if (!$adgroup_tactics_map->add($adgroup_tatics_map_data)) {
				// 	//添加失败,抛出错误
				// 	throw new Exception("adgroup_tatics_map添加失败!",1);
				// }	
				$notify['code'] = 1;
				$notify['msg'] = '添加成功!';     
			}
			//提交事务
			$tactics->commit();
			$this->display_json($notify);		
        }catch(Exception $e){
        	if ($tactics) {
        		$tactics->rollback();
        	}
		    $this->ranking->printError($e);
		    $this->display_json(array('code' => 0, 'msg' => $this->ranking->getErrorMessage($e)));
        }
	}	
	public function show()
	{
		$this->loadJS('msg/msg','jquery.cookie', 'ranking/rankings_list');
		$list = $this->_showTacticsByUserId();
		$pageHtml = page_html($list['pageNow'], $list['rowCount'], $list['pageSize']);
		$this->assign('list', $list);
		$this->assign('pageHtml', $pageHtml);
		$this->display();
	}

	public function tacticsById()
	{
		$tactics_id = (int)$this->_param('tactics_id');
		$sql = "SELECT
					t.tactics_id,t.user_id,
					t.tactics_name,t.tactics_status,
					t.premium,t.campaign_period,
					t.heighest_price,t.path,
					t.from,t.to,
					w.keyword_id,w.want_rank,
					w.doing,k.adgroup_id,
					k.campaign_id,a.num_iid,
					k.word,a.title
				FROM
					want_rank AS w
				JOIN tactics AS t ON t.tactics_id = w.tactics_id
				JOIN `keywords{$this->me['user_id']}` AS k ON k.keyword_id = w.keyword_id
				JOIN adgroups AS a ON a.adgroup_id = k.adgroup_id
				WHERE
					t.tactics_id = {$tactics_id} AND
					t.user_id = {$this->me['user_id']}";
		$res = M()->query($sql);
		// if($res) {
		// 	$condition['keywords'] = $res;
		// 	$condition['product_id'] = null;
		// 	$keywords = R('Keyword/keywordsRealRank', array($condition), 'Event');
		// }
		$return = array(
				'total_items' => 0
			);
		if($res) {
			$return['total_items'] = count($res);
			foreach ($res as $key => $item) {
				if(!isset($return['kawei_info'])) {
					$return['kawei_info'] = array(
							'tactics_id' => $item['tactics_id'],
							'kawei_name' => $item['tactics_name'],
							'from' => date('Y-m-d', $item['from']).'T'.date('H:i', $item['from']),
							'to' => date('Y-m-d', $item['to']).'T'.date('H:i', $item['to']),
							'campaign_period' => ((int)$item['campaign_period'])/60, // 秒转为分
							'premium' => (strpos($item['premium'], '%') === false) ? array('type'=> 1,'value' => floatval($item['premium'])/100) : array('type' => 2, 'value' => floatval(str_replace('%', '', $item['premium']))*100),
							'heighest_price' => ((int)$item['heighest_price'])/100 // 分转为元
						);
				}
				$return['keyword_info'][$item['keyword_id']] = array(
						'keyword_id' => $item['keyword_id'],
						'word' => $item['word'],
						'want_rank' => $item['want_rank'],
						'adgroup_id' => $item['adgroup_id'],
						'campaign_id' => $item['campaign_id'],
						'num_iid' => $item['num_iid'],
					);
			}
			// $return['items'] = $res;
		}
		$this->display_json($return);
	}

	public function ranking_list()
	{
		$this->loadJS('msg/msg','jquery.cookie', 'ranking/rankings_list');
		$this->display();
	}

	public function ranking_detail()
	{
		$tactics_id = $this->_param('tactics_id');
		$this->tactics_id = $tactics_id;
		$tactics = M('tactics');
		$this->tactics = $tactics->find(array('tactics_id' => $tactics_id));
		$this->loadJS('daterangepicker', 'date', 'msg/msg', 'ranking/ranking_detail');
		$this->display();
	}
}